package cn.edu.zzuli.stack;

public class LinkStack<T> {
    //栈内元素个数
    private int size;
    //栈顶虚拟节点
    private Node<T> top = new Node("");

    //判断栈是否为null
    public boolean isEmpety() {
        return size == 0;
    }

    //入栈，使用头插法
    public void push(T value) {
        Node<T> node = new Node(value);
        if (isEmpety()) {
            top.setNext(node);
        }else {
            node.setNext(top.getNext());
            top.setNext(node);
        }
        size++;
    }

    //获取栈顶元素，但是不出栈
    public T top() {
        if (isEmpety()) {
            System.out.println("栈为空");
            return null;
        }

        return top.getNext().getData();
    }

    //栈顶元素出栈
    public T pop() {
        if (isEmpety()) {
            return null;
        }
        Node<T> node = top.getNext();
        top.setNext(top.getNext().getNext());
        size--;
        return node.getData();
    }

    //遍历栈内元素，但不出栈
    public void list() {
        if (isEmpety()) {
            System.out.println("栈空");
            return;
        }

        Node<T> temp = top.getNext();

        while (temp != null) {
            System.out.println(temp.getData());
            temp = temp.getNext();
        }
    }

    //获取栈内元素个数
    public int getSize() {
        return this.size;
    }

}

class Node<T> {
    private T data;
    private Node<T> next;

    public Node(T data) {
        this.data = data;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Node<T> getNext() {
        return next;
    }

    public void setNext(Node<T> next) {
        this.next = next;
    }
}
